<?php

namespace App\Http\Controllers\Api;

use App\Models\Order;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;

class WeiXinPayController extends Controller
{

	public function orderPay(Request $request)
	{
		try{
            return response()->json([
                   'code'=>200,
                   'msg'=>'功能暂停使用，请使用余额支付',
            ]);
			$order_sn = $request->input('order_sn');

			$order = Order::query()->where([
				'status'=>0,
				'order_sn'=>$order_sn,
				'user_id'=>auth('api')->id()
			])->first();


			if(!$order){
				return response()->json([
					'code'=>404,
					'msg'=>'订单不存在',
				]);
			}

			require app_path('Extensions/WxPay/WxPay.JsApiPay.php');

			$tools = new \JsApiPay();
//			$openId = $tools->GetOpenid();

			$input = new \WxPayUnifiedOrder();
			$input->SetBody("测试商城");
			$input->SetAttach("test");
			$input->SetOut_trade_no($order['order_sn'] . mt_rand(10,1999));

			$total_price = $order->price_total * 100;
			$input->SetTotal_fee((int)$total_price);
			$input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
			$input->SetTrade_type("MWEB");

			//H5支付的时候
			$secne_info = [
				'h5_info'=>[
					'type'=>'Wap',
					'wap_url'=>'https://17hxg.com',
					'wap_name'=>'测试商城'
				]
			];
			$input->SetSceneInfo(json_encode($secne_info));

			//jsapi必须加入用户OPENID
//			$input->SetTrade_type("JSAPI");
//			$input->SetOpenid(auth('api')->user()->wx_openid);

			$config = new \WxPayConfig();

			$tongyiOrder = \WxPayApi::unifiedOrder($config,$input);

			\Illuminate\Support\Facades\Log::info('【支付】订单号:' . $order['order_sn'] . json_encode($tongyiOrder));

			if($tongyiOrder['return_code'] != 'SUCCESS'){
				return response()->json([
					'code'=>400,
					'msg'=>'支付失败，请联系管理员处理'
				]);
			}

			//js api下单的时候需要这些
			//$jsApiParameters = $tools->GetJsApiParameters($tongyiOrder);

			return response()->json([
				'code'=>200,
				'msg'=>'ok',
				'data'=>
				$tongyiOrder
			]);
		}catch (\Exception $e){
			return response()->json([
				'code'=>404,
				'msg'=>$e->getMessage(),
			]);
		}



	}

	/**
	 * 异步回调验证数据
	 * User: Clannad ~ ☆
	 * DataTime：2020/3/21 0021 16:04
	 * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
	 */
	public function notify()
	{
		$notifyData = file_get_contents('php://input');

		//数据先转为数组
		//将XML转为array
		//禁止引用外部xml实体
		libxml_disable_entity_loader(true);
		$notifyData = json_decode(json_encode(simplexml_load_string($notifyData, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

		//开始验签逻辑
		if($notifyData['return_code'] == "SUCCESS" && $notifyData['result_code'] == "SUCCESS"){
			//除去签名参数 然后验签
			$xmlSign = '';

			foreach ($notifyData as $k => $v) {
				if($k == 'sign'){
					$xmlSign = $notifyData[$k];
					unset($notifyData[$k]);
				}
			}

			//变成url参数形式
			$urlParams = http_build_query($notifyData);

			//如果是MD5 则里面就使用MD5加密
			$config = new \WxPayConfig();
			$sign = strtoupper(hash_hmac("sha256",$urlParams ,$config->GetKey()));

			if($xmlSign == $sign){
				//验签成功逻辑

				//判断订单 判断金额 判断订单状态

				echo 'SUCCESS';
			}else{

			}
		}else{
			\Illuminate\Support\Facades\Log::info('【订单支付回调错误】：' . json_encode($notifyData));
		}
	}


	/**
	 * 将xml转为array
	 * @param string $xml
	 * @throws WxPayException
	 */
	public function FromXml($xml)
	{
		if(!$xml){
			Log::info('');
		}

	}

	protected $config = [
		'app_id' => 'wxa7a920ba9bec529d', // 公众号 APPID
//		'miniapp_id' => 'wxb3fxxxxxxxxxxx', // 小程序 APPID
		'mch_id' => '1578491061',
//		'key' => '7a23aa8a48ca305faff3dc6bb5e3a6fc',
		'key' => '6837926a3b4e94f6b8579da528944477',
//		'notify_url' => 'https://yanda.net.cn/notify.php',
		'cert_client' => './cert/apiclient_cert.pem', // optional，退款等情况时用到
		'cert_key' => './cert/apiclient_key.pem',// optional，退款等情况时用到
		'log' => [ // optional
			'file' => './logs/wechat.log',
			'level' => 'debug', // 建议生产环境等级调整为 info，开发环境为 debug
			'type' => 'single', // optional, 可选 daily.
			'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
		],
		'http' => [ // optional
			'timeout' => 5.0,
			'connect_timeout' => 5.0,
			// 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
		],
		'mode' => 'normal', // optional, dev/hk;当为 `hk` 时，为香港 gateway。
	];

	public function orderPay2(Request $request)
	{
		$order_sn = $request->input('order_sn');

		$order = Order::query()->where([
			'status'=>0,
			'order_sn'=>$order_sn,
			'user_id'=>auth('api')->id()
		])->first();


		if(!$order){
			return response()->json([
				'code'=>404,
				'msg'=>'订单不存在',
			]);
		}


		$pay_order = [
			'out_trade_no' => $order_sn,
			'total_fee' => $order['total_price'] * 100, // **单位：分**
			'body' => 'clannad商城下单测试',
		];

		$this->config['notify_url'] = 'https://yanda.net.cn/notify.php';//自定义回调地址

		try{
			$pay =  Pay::wechat($this->config)->mp($pay_order);

			Log::info(json_encode($pay));
			Log::info($pay);

			return response()->json([
				'code'=>404,
				'msg'=>'订单不存在',
				'data'=>[
					'appId'=>$pay->appId,
					'timeStamp'=>$pay->timeStamp,
					'nonceStr'=>$pay->nonceStr,
					'package'=>$pay->package,
					'signType'=>$pay->signType,
				]
			]);

		}catch (GatewayException $exception){
			Log::info(date("H:i:s") . " 订单{order['out_trade_no']}");
			Log::info('支付错误消息：' . $exception->getMessage());

			return response()->json([
				'code'=>404,
				'msg'=>$exception->getMessage(),
			]);
		}

		// $pay->appId
		// $pay->timeStamp
		// $pay->nonceStr
		// $pay->package
		// $pay->signType
	}

//	public function notify()
//	{
//		$pay = Pay::wechat($this->config);
//
//		try{
//			$data = $pay->verify(); // 是的，验签就这么简单！
//
//			Log::debug('Wechat notify', $data->all());
//		} catch (\Exception $e) {
//			// $e->getMessage();
//		}
//
//		return $pay->success()->send();// laravel 框架中请直接 `return $pay->success()`
//	}
}
